import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';

// 定义待办事项接口
interface Todo {
  id: string;
  text: string;
  completed: boolean;
  createdAt: Date;
}

function App() {
  // 状态管理
  const [todos, setTodos] = useState<Todo[]>([]);
  const [newTodoText, setNewTodoText] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  // API基础URL
  const API_URL = 'http://localhost:5000/api/todos';

  // 获取所有待办事项
  const fetchTodos = async () => {
    try {
      setLoading(true);
      const response = await axios.get<Todo[]>(API_URL);
      setTodos(response.data);
      setError('');
    } catch (err) {
      console.error('获取待办事项失败:', err);
      setError('获取待办事项失败，请检查后端服务是否运行');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchTodos();
  }, []);

  // 添加新的待办事项
  const addTodo = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!newTodoText.trim()) return;
    
    try {
      const response = await axios.post<Todo>(API_URL, { text: newTodoText });
      setTodos([...todos, response.data]);
      setNewTodoText('');
    } catch (err) {
      console.error('添加待办事项失败:', err);
      setError('添加待办事项失败');
    }
  };

  // 切换待办事项完成状态
  const toggleTodoStatus = async (id: string) => {
    try {
      const todo = todos.find(t => t.id === id);
      if (!todo) return;
      
      const response = await axios.put<Todo>(`${API_URL}/${id}`, {
        completed: !todo.completed
      });
      
      setTodos(todos.map(todo => 
        todo.id === id ? response.data : todo
      ));
    } catch (err) {
      console.error('更新待办事项状态失败:', err);
      setError('更新待办事项状态失败');
    }
  };

  // 删除待办事项
  const deleteTodo = async (id: string) => {
    try {
      await axios.delete(`${API_URL}/${id}`);
      setTodos(todos.filter(todo => todo.id !== id));
    } catch (err) {
      console.error('删除待办事项失败:', err);
      setError('删除待办事项失败');
    }
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>待办事项列表</h1>
      </header>
      
      <main className="App-main">
        {/* 添加待办事项表单 */}
        <form onSubmit={addTodo} className="todo-form">
          <input
            type="text"
            value={newTodoText}
            onChange={(e) => setNewTodoText(e.target.value)}
            placeholder="添加新的待办事项..."
            className="todo-input"
          />
          <button type="submit" className="todo-button">添加</button>
        </form>
        
        {/* 错误提示 */}
        {error && <div className="error-message">{error}</div>}
        
        {/* 加载状态 */}
        {loading ? (
          <div className="loading">加载中...</div>
        ) : (
          /* 待办事项列表 */
          <ul className="todo-list">
            {todos.length === 0 ? (
              <li className="empty-message">暂无待办事项</li>
            ) : (
              todos.map(todo => (
                <li key={todo.id} className={`todo-item ${todo.completed ? 'completed' : ''}`}>
                  <div className="todo-content">
                    <input
                      type="checkbox"
                      checked={todo.completed}
                      onChange={() => toggleTodoStatus(todo.id)}
                      className="todo-checkbox"
                    />
                    <span className="todo-text">{todo.text}</span>
                  </div>
                  <button
                    onClick={() => deleteTodo(todo.id)}
                    className="delete-button"
                  >
                    删除
                  </button>
                </li>
              ))
            )}
          </ul>
        )}
      </main>
    </div>
  );
}

export default App;
